package com.sbl.bajw.common;

import java.util.HashMap;
import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.util.JsonUtil;

public class MyBatisDao {
	
	  private SqlSessionTemplate sqlSession;
	
	  public void setSqlSession(SqlSessionTemplate sqlSession)
	  {
	    this.sqlSession = sqlSession;
	  }
	  
	  public <T> String selectPage(Class<T> entityClass,HashMap<String, Object> parm, String statement)
	  {
		 Page page = RequestUnit.getPage();
		 if(parm == null){
			 parm = new HashMap<String, Object>();
		 }
		 int total = selectForInt(entityClass,parm,statement+"_total");
		 int pageCount = (int) Math.ceil((double)total/page.getPageSize());
		
		 parm.put("pageParameter", page);
		 statement = entityClass.getName()+"."+statement;
		 List<?> list = sqlSession.selectList(statement, parm);
		
		 String data = JsonUtil.ConvertArrayToJson(list);
		 String result = "{\"pageSize\":\""+page.getPageSize()+"\",\"pageCount\":\""+pageCount+"\",\"pageIndex\":\""+page.getPageIndex()+"\",\"total\":\""+total+"\",\"data\":"+data+"}";
	     return result;
	  } 
	  
	  public <T> int selectForInt(Class<T> entityClass, Object params, String statement)
	  {
	    int returnInt = 0;
	
	    statement = entityClass.getName()+"."+statement;
	    Object intObj = this.sqlSession.selectOne(statement, params);
	    if (intObj != null) {
	      returnInt = ((Integer)intObj).intValue();
	    }
	
	    return returnInt;
	  }
}
